/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.workflow.rpc.dictionary;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import org.apache.servicecomb.provider.pojo.RpcSchema;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RpcSchema(schemaId = "workFlowRemoteCallServeManager")
public class WorkFlowRemoteCallServeManagerImpl implements WorkFlowRemoteCallServeManager {

    @Override
    public Object doGetDynaBean(String id, String tableCode) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        try {
            return metaService.selectOneByPk(tableCode, id);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Object doUpdateBean(Object bean, String id, String tableCode) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        try {
            Map<String, Object> values = (Map<String, Object>) bean;
            DynaBean dynaBean = new DynaBean(tableCode, true);
            String pkCode = dynaBean.getPkCode();
            values.put(pkCode, id);
            values.put(BeanService.KEY_TABLE_CODE, tableCode);
            dynaBean.setValues((HashMap<String, Object>) values);
            return metaService.update(dynaBean);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void deployClearBusinessDataWorkFlowFiledInfo(String tableCode, String modelKey) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        if (Strings.isNullOrEmpty(modelKey)) {
            return;
        }
        DynaBean dynaBean = new DynaBean();
        dynaBean.setStr("SY_STARTEDUSER", "");
        dynaBean.setStr("SY_STARTEDUSERNAME", "");
        dynaBean.setStr("SY_APPROVEDUSERS", "");
        dynaBean.setStr("SY_APPROVEDUSERNAMES", "");
        dynaBean.setStr("SY_PREAPPROVUSERS", "");
        dynaBean.setStr("SY_LASTFLOWINFO", "");
        dynaBean.setStr("SY_PREAPPROVUSERNAMES", "");
        dynaBean.setStr("SY_LASTFLOWUSER", "");
        dynaBean.setStr("SY_LASTFLOWUSERID", "");
        dynaBean.setStr("SY_WFWARN", "");
        dynaBean.setStr("SY_PIID", "");
        dynaBean.setStr("SY_PDID", "");
        dynaBean.setStr("SY_WARNFLAG", "");
        dynaBean.setStr("SY_CURRENTTASK", "");
        dynaBean.setStr("SY_AUDFLAG", "NOSTATUS");
        metaService.update(dynaBean, ConditionsWrapper.builder().table(tableCode).like("SY_PDID", modelKey));
    }

    @Override
    public void updateListBeanWFAssignee(List<DynaBean> list) {
        Map<String, DynaBean> listMap = new HashMap<>();
        for (DynaBean dynaBean : list) {
            listMap.put(dynaBean.getStr("BUSINESS_KEY"), dynaBean);
        }
        Map<String, List<DynaBean>> tables = new HashMap<>();
        for (DynaBean dynaBean : list) {
            String tableCode = dynaBean.getStr("TABLE_CODE");
            List<DynaBean> beans = tables.computeIfAbsent(tableCode, k -> new ArrayList<>());
            beans.add(dynaBean);
        }

        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        BeanService beanService = SpringContextHolder.getBean(BeanService.class);
        for (String tableCode : tables.keySet()) {
            List<DynaBean> list1 = tables.get(tableCode);
            List<String> ids = new ArrayList<>();
            for (DynaBean dynaBean : list1) {
                ids.add(dynaBean.getStr("BUSINESS_KEY"));
            }
            String pkName = beanService.getPKeyFieldNamesByTableCode(tableCode);
            List<DynaBean> list2 = metaService.select(tableCode, ConditionsWrapper.builder().in(pkName, ids));

            for (DynaBean dynaBean : list2) {
                String SY_PREAPPROVUSERNAMES = dynaBean.getStr("SY_PREAPPROVUSERNAMES");
                String SY_PREAPPROVUSERS = dynaBean.getStr("SY_PREAPPROVUSERS");
                String pkValue = dynaBean.getPkValue();
                DynaBean updateInfo = listMap.get(pkValue);
                String NEW_ASSIGNEE_ = updateInfo.getStr("NEW_ASSIGNEE_");
                String NEW_USER_NAME = updateInfo.getStr("NEW_USER_NAME");
                String ASSIGNEE_ = updateInfo.getStr("ASSIGNEE_");
                String USER_NAME = updateInfo.getStr("USER_NAME");
                Map<String, String> map = replaceValue(SY_PREAPPROVUSERNAMES, SY_PREAPPROVUSERS, NEW_ASSIGNEE_, NEW_USER_NAME, ASSIGNEE_, USER_NAME);
                DynaBean dynaBean1 = new DynaBean();
                dynaBean1.setStr("SY_PREAPPROVUSERNAMES", map.get("userNames"));
                dynaBean1.setStr("SY_PREAPPROVUSERS", map.get("userIds"));
                metaService.update(dynaBean1, ConditionsWrapper.builder().table(dynaBean.getTableCode()).eq(dynaBean.getPkCode(), dynaBean.getPkValue()));
//                metaService.update(dynaBean);
            }
        }
    }


    private static Map<String, String> replaceValue(String SY_PREAPPROVUSERNAMES, String SY_PREAPPROVUSERS,
                                                    String NEW_ASSIGNEE_, String NEW_USER_NAME, String ASSIGNEE_, String USER_NAME) {
        String[] userIs = SY_PREAPPROVUSERS.split(",");
        String[] userNames = SY_PREAPPROVUSERNAMES.split(",");
        for (int i = 0; i < userIs.length; i++) {
            if (userIs[i].equals(ASSIGNEE_)) {
                userIs[i] = NEW_ASSIGNEE_;
                userNames[i] = NEW_USER_NAME;
            }
        }
        SY_PREAPPROVUSERS = String.join(",", userIs);
        SY_PREAPPROVUSERNAMES = String.join(",", userNames);
        System.out.println(SY_PREAPPROVUSERS);
        System.out.println(SY_PREAPPROVUSERNAMES);
        Map<String, String> result = new HashMap<>();
        result.put("userIds", SY_PREAPPROVUSERS);
        result.put("userNames", SY_PREAPPROVUSERNAMES);
        return result;
    }

}
